package com.my.mybasefragment.base_fragment;


import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
 * 项目名称：给ViewPager使用的fragment
 * 创建人：mwb
 * 创建时间：2018/6/19 8:46
 */

public abstract class BaseFragmentViewPager extends Fragment {
    private String TAG = "mwb";

    protected abstract int setView();

    protected abstract void init(View view);

    protected abstract void initData(Bundle savedInstanceState);

    /**
     * Resume是否可用
     */
    protected abstract void onCurrentResumeOk();

    /**
     * 是否打印Log
     */
    private boolean isDebug = true;

    /**
     * 是否为当前的fragment
     * onResume 是否可用
     */
    private boolean currentFragmentOnResume;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(setView(), container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        init(view);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initData(savedInstanceState);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (currentFragmentOnResume) { // onResume 可以使用
            LogUtil("BaseFragment onResume if");
            onCurrentResumeOk();
        } else {
            LogUtil("BaseFragment onResume else");
            return;
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);

        if (isVisibleToUser) {  //在最前端界面显示
            LogUtil("BaseFragment setUserVisibleHint if");
            currentFragmentOnResume = true;
        } else { // 不在最前端界面显示
            LogUtil("BaseFragment setUserVisibleHint else");
            currentFragmentOnResume = false;
        }
    }

    public void LogUtil(String msg) {
        if (isDebug) {
            Log.i(TAG, msg);
        }
    }
}
